package com.student.filter;



        import javax.servlet.*;
        import javax.servlet.annotation.WebFilter;
        import javax.servlet.annotation.WebInitParam;
        import java.io.IOException;

/**
 * @author 康娜的小肥腿
 */
@WebFilter(filterName = "SetCharacterEncodingFilter",
        value = {"/*"}, // value={"*.do","*.action"}
        initParams = { // 为此过滤器提供的初化参数
                @WebInitParam(name="encoding",value = "utf-8"),
                @WebInitParam(name="nickName",value = "scott"),
                @WebInitParam(name="age",value = "22")
        })
public class SetCharacterEncodingFilter implements Filter {

    private String encoding = "";

    public void destroy() {
    }

    /**
     * 过滤处理
     * @param request
     * @param response
     * @param chain     过滤链组件
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 解决中文输入乱码问题
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        // 将请求和响应对象转交给后续的Web组件(JSP,Servlet,Filter)继续处理
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("过滤器的初始化方法，即在此过滤器对象补创建出来后调用的方法");
        encoding = config.getInitParameter("encoding");

        String nickName = config.getInitParameter("nickName");
        String age = config.getInitParameter("age");
        System.out.printf("NickName: %s,  Age: %s", nickName, age);
    }

}
